<?php
namespace Web\Controller;
use Think\Controller;
use Web\Logic\MemberLogic;
class MemberController extends BaseController {

	public function index(){
		//实例化Logic
		$logic = new MemberLogic();
		// 接收参数  用户名
		$susername = trim($_POST['susername']);
		//判断参数
		if($susername)
		{
			$wdata['m.username'] = array("like","%".$susername."%");
		}

        $andStr = "";
        if (!in_array("1000", $this->mFunction_list)) {
            $admin_role = M('role_info')->where(array('function_id'=>array('like','%1000%')))->getField('roleid',true);
            $wdata['m.roleid'] = array('not in',$admin_role);
        }
		//查询总数量

		$count = $logic->selNum($wdata);
		$Page  = $this->getpage($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$Page->parameter['susername'] = $susername;
		$show  = $this->bootstrap_page_style($Page->show());

		//模版包集合
		$mobans = M('tpl_module')->getField('id,name');

		//查询数据
		$rolerows = $logic->indexList($wdata, $Page);
		$this->assign('rolelist',$rolerows);// 赋值数据集
		$this->assign('susername',$susername);//
		$this->assign('page',$show);// 赋值分页输出
		$this->assign('mobans',$mobans);// 赋值分页输出

        $this->assign("cat","用户列表");
		$this->display(); // 输出模板
	}

	/**
	 * @desc 添加用户
	 * @param rolename 用户名
	 * @param notes 备注
	 */
	public function add()
	{
		//实例化 logic
		$logic = new MemberLogic();
		//获取提交隐含域
		$subs = $_REQUEST['sub'];
		//接受用户名
		$data = $_REQUEST['data'];
		if($data)
		{
			//判断用户名是否存在
			$row  = $logic->selNum($data);
			if($row >0)
			{
				$this ->error('用户名已存在');
				exit;
			}
			else
			{
				//判断密码不为空 md5加密
				if($data['password']){
					$data['password'] = md5($data['password']);
				}
				$data['updatedatetime'] = date("Y-m-d H:i:s");
				$r = $logic->addDataSql($data);
				//判断是否添加成功
				if($r){
                    $this->updateRole($data['roleid'],$r);
					$this->success('保存成功');
					exit;
				}
			}

		}
		//查询用户
		$roleData = $logic->selRoleData();
		//定义模板变量
		$this->assign("roleData",$roleData);

         $department_list = $this->getDepartment();
        $this->assign('department_list', $department_list);
		//调用模板
		$this->display();
	}

	/**
	 * @desc 用户删除
	 * @param roleid 用户id
	 */
	public function deletes()
	{
		//接受 roleid
		$id = $_REQUEST['id'];
		//实例化 logic
		$logic = new MemberLogic();
		$des3 = $logic->delDataSql($id);
		if($des3)
		{
			$this->success('删除成功');
		}
	}

	/**
	 * @desc 用户修改
	 * @param roleid 用户id
	 */
	public function edit($userid=0){
        if(IS_POST){
			$act = I('act', 'add');
			$rules = array(
                array('username','require','用户名称必填！'),
                array('username','','用户名称已经存在！',0,'unique'),
                array('company','require','公司名称必填！'),
           );
			
			$Member = M('member');
			if (!$Member->validate($rules)->create()){
				 exit('<script>parent.notify("error","提示","' . $Member->getError() . '");</script>');
			}else{
                $module_ids = I('module_ids/a');
                $Member->module_ids = implode(',', $module_ids);
				$Member->updated_at = date('Y-m-d H:i:s');
				
				if($act == 'add'){
                    $Member->created_at = date('Y-m-d H:i:s');
					$ins = $Member->add();
					$user_id = $ins;
                    writeLog(session(C('SESSION_ADMIN_ID')), 2, '创建用户', '', $ins);
				} else {
					$ins = $Member->save();
					$user_id = $userid;
                    writeLog(session(C('SESSION_ADMIN_ID')), 2, '修改用户', '', I('id'));
				}
			}

			if($ins !== false){
				if($act == 'edit'){
					//update member info
					$MemberInfo = M('member_info');
					$map['user_id'] = $user_id;
					$data['company'] = I('company');
					$rs = $MemberInfo->where($map)->find();
					if($rs){
						$MemberInfo->where($map)->save($data);
					} else {
						$data['user_id'] = $user_id;
						$MemberInfo->add($data);
					}

				} else {
					//add member info
					$data['user_id'] = $ins;
					$data['company'] = I('company');
					M('member_info')->add($data);
				}
				echo '<script>parent.notify("success","提示","用户保存成功！");parent.location="' . U('index') . '";</script>';
			} else {
				echo '<script>parent.notify("error","提示","用户保存失败！");</script>';
			}
		} else {
			$vo = M('member')->alias('m')
				->join('LEFT JOIN '.C('DB_PREFIX').'member_info i ON m.userid=i.user_id')
				->where(array('userid'=>$userid))
				->find();

			//取得角色
			$andStr = "";
            $role_id = session('roleid');
            $admin_role_id = C('ADMIN_ROLE');
            $admin_role = explode(",", $admin_role_id);
            if(!in_array($role_id,$admin_role)){
                $andStr = " and roleid not in($admin_role_id)";
            }

            $Role = M("role");
            $roleData =  $Role->field("roleid,rolename")
                       ->where("isforbidden = 0".$andStr)
                       ->order('roleid ASC')
                       ->select();

			$this->assign("roleData", $roleData);
			$this->assign('vo', $vo);
			$this->display();
		}
    }

    function updateRole($roleid,$userid){

        //先删除掉之前的所有权限
         $itemName = "user_id";
         $table_name ="device_control_auth";
         $table_param_name ="device_param_control_auth";

         //先删除掉主表的
         $mod = M($table_name);
         $where[$itemName] = $userid;
         $mod->where($where)->delete();
         //再删除具体参数表的
         $mod_parm = M($table_param_name);
         $mod_parm->where($where)->delete();

         //然后将主表的角色的赋予用户
         $sql = "INSERT INTO ly_device_control_auth(user_id,class_id,cpn_id,control_status)(SELECT $userid as user_id,class_id,cpn_id,control_status FROM ly_role_control_auth WHERE role_id = $roleid)";
         $mod->execute($sql);
         $sql ="INSERT INTO ly_device_param_control_auth (user_id,class_id,cpn_id,parm_id,control_status)(SELECT $userid AS user_id,class_id,cpn_id,parm_id,control_status FROM  ly_role_param_control_auth  WHERE role_id = $roleid)";
         $mod->execute($sql);

    }
	/**
	 * 页面显示
	 * @access public
	 * @author:weihongwei <2014-02-10>
	 * @return void
	 */
	public function editpwd() {
		if(IS_POST){
			$pwd = I('pwd');
			$repwd = I('repwd');
			if($pwd != $repwd) exit('<script>parent.notify("error","提示","密码与确认密码不相同！");</script>');
			$map['userid'] = $this->mAdminId;
			$res = M('member')->where($map)->setField('password', md5($pwd));
			if($res !== false){
				exit('<script>parent.notify("success","提示","保存成功！");</script>');
			} else {
				exit('<script>parent.notify("error","提示","保存失败！");</script>');
			}
		} else {

			//获取session中的name值：
			$user_name = $_REQUEST["username"]?$_REQUEST["username"]:$this->mAdminName;
			$this->assign("name", $user_name);

			//1.1.2 加载模板，修改密码页面显示
			$this->display();
		}
	}

	/**
	 * 后台添加用户检测用户名是否被注册
	 * @access public
	 * @param $name string  要检测的用户名
	 * @return blue
	 * @note:
	 */
	public function checkUserName() {
		//取得用户名
		$data['username'] = $_REQUEST["userName"];
		//实例化模块
		//实例化 logic
		$logic = new MemberLogic();
		//判断用户名是否存在
	    $row  = $logic->selNum($data);
		$rows[num] = $row;
		$this->ajaxReturn($rows);
	}

    private function getDepartment(){
        $arr = M('m_department')->where(array('is_show'=>1))->field('id,name as name,parent_id as pid')->order('name asc')->select();
        $list = array_map(function($v){return array('id'=>$v['id'], 'name'=>$v['name'], 'pId'=>$v['pid']);}, $arr);
        $list =  json_encode($list);
        return $list;
    }

	public function sendMAC(){
		$arr = M('member')->where("mac IS NOT NULL AND mac<>''")->getField('mac', true);
		//$arr = array_values(array_filter($arr));
		$data['date'] = time();
		$data['msg_id'] = 0x28;
		$data['msg_type_id'] = 0x28;
		$data['msg_value'] = json_encode($arr);
		$ins = M('msg_web_to_soft')->add($data);
		if($ins){
			echo '1';
		} else {
			echo '0';
		}
	}

	public function getModule(){
        
        $results = array();

		$list = M('tpl_module')->field('id,name')->select();

		$results = array_map(function($v){
			return array('id'=>$v['id'], 'text'=>$v['name']);
		}, $list);

		$this->ajaxReturn(compact('results'));
    }

	public function getSelModule(){
        $userid = I('userid', 0);

		$results = array();

		$module_ids = M('member')->where(array('userid'=>$userid))->getField('module_ids');
		if(empty($module_ids)) $this->ajaxReturn(compact('results'));

		$map['id'] = array('in', $module_ids);
		$list = M('tpl_module')->where($map)->field('id,name')->select();
		$results = array_map(function($v){
			return array('id'=>$v['id'], 'text'=>$v['name']);
		}, $list);

		$this->ajaxReturn(compact('results'));
    }
}